<template>
    <el-dialog :visible.sync="dialogFormVisible"
               title="上传文件"
               :before-close="onClose"
               destroy-on-close
               :pid="pid"
               :files="files"
    >
      <el-form ref="form" :model="form" :rules="rules" >
        <el-form-item label="上传文件" prop="file">
          <el-upload
              :class="{'uploadHide':showUploadBtn}"
              ref="upload"
              :action="uploadUrl()"
              name="file"
              drag
              :data="uploadForm"
              :on-change="handleChange"
              :on-error="handleError"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              :before-upload="handleBeforeUpload"
              :auto-upload="false"
              :headers="tokenHeader()"
          >
            <i class="el-icon-upload" v-show="fileList.length === 0"></i>
            <div class="el-upload__text" v-show="fileList.length === 0">将文件拖到此处，或<em>点击上传</em></div>
            <!-- <el-button slot="trigger" size="small" >选取文件</el-button> -->
            <div slot="tip" class="el-upload__tip" style="color:red">上传文件只能是 pdf、md 格式!</div>
          </el-upload>
          <el-form-item label="文件标题" prop="title">
            <el-input v-model="form.title"></el-input>
          </el-form-item>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onClose">取 消</el-button>
        <el-button type="primary" @click="submitUpload">确 定</el-button>
      </div>
    </el-dialog>
</template>

<script>
export default {
  name: "AddFileModal",
  props: {
    dialogFormVisible: Boolean,
    pid: Number,
    files: []//当前目录下的文件
  },
  data() {
    return {
      allowFileType: ["pdf", "md"],
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { max: 50, message: '长度不能超过50', trigger: 'blur' }
        ]
      },
      form: {
        pid: undefined,
        title:'',
      },
      fileList: [],
      header: {}
    }
  },
  methods: {
    onClose() {
      this.$refs['form'].resetFields();
      this.$emit('onClose');
    },
    onSubmit() {
      this.onClose();
    },
    resetForm() {
      this.$refs['form'].resetFields();
    },
    //导入接口地址
    uploadUrl: function() {
      return process.env.VUE_APP_BASE_URL + '/file';
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    //文件上传成功触发
    handleSuccess(response) {
      if(response.success){
        this.$message.success(response.message);
        this.$emit("onSuccess");
        this.onClose();
        return;
      }
      if(response.code === 401){
        //需要登录
        window.localStorage.setItem('showLogin', 'true');
      }
      this.$message.error(response.message);
    },
    //文件上传失败触发
    handleError(response, file, fileList) {
      console.log(response, file, fileList)
      this.$message.error(response.message);
    },
    //上传前对文件类型的判断
    handleBeforeUpload(file) {
      this.form.fileName = file.name;
      let split = file.name.split(".");
      let extension = split[split.length - 1];
      if (this.allowFileType.filter(type => type === extension).length === 0) {
        this.$message.warning('上传文件只能是' + this.allowFileType.toString() + ' 格式!');
        return false;
      }
      return true;
    },
    tokenHeader() {
      let token = window.localStorage.getItem("token");

      if (!token) {
        return {};
      }
      this.header['LIBRARY|TOKEN'] = token;
      return this.header;
    },
    //表单提交
    submitUpload() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          //判断文件标题是否重复
          if (this.files.filter(file => file.title === this.form.title).length > 0) {
            this.$message.warning("文件标题已存在");
            return false;
          }
          //判断是否上传文件
          if (!this.fileList || this.fileList.length === 0) {
            this.$message.warning("请上传文件");
            return false;
          }
          //触发组件的action
          this.$refs['upload'].submit();
        } else {
          return false;
        }
      });
    }
  },
  computed: {
    // 这里定义上传文件时携带的参数，即表单数据
    uploadForm() {
      return this.form
    },
    showUploadBtn() {
      return this.fileList && this.fileList.length > 0;
    }
  },
  mounted() {
    this.form.pid = this.pid;
  }
}
</script>

<style scoped>

</style>